const express = require('express');
const { v4: uuidv4 } = require('uuid');
const router = express.Router();

// 获取餐厅列表（分页）
router.get('/', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, category, search } = req.query;
    const offset = (page - 1) * pageSize;
    
    let query = req.supabase.from('restaurants').select('*', { count: 'exact' });
    
    // 添加分类过滤
    if (category) {
      query = query.eq('category', category);
    }
    
    // 添加搜索过滤
    if (search) {
      query = query.ilike('name', `%${search}%`);
    }
    
    // 添加分页和排序
    query = query.range(offset, offset + parseInt(pageSize) - 1).order('created_at', { ascending: false });
    
    const { data, error, count } = await query;
    
    if (error) throw error;
    
    const totalPages = Math.ceil(count / pageSize);
    
    res.json({
      success: true,
      data: {
        data,
        total: count,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        totalPages
      },
      message: '餐厅列表获取成功'
    });
  } catch (error) {
    console.error('获取餐厅列表失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '获取餐厅列表失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

// 获取所有餐厅
router.get('/all', async (req, res) => {
  try {
    const { data, error } = await req.supabase
      .from('restaurants')
      .select('*')
      .order('created_at', { ascending: false });
    
    if (error) throw error;
    
    res.json({
      success: true,
      data,
      message: '所有餐厅获取成功'
    });
  } catch (error) {
    console.error('获取所有餐厅失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '获取所有餐厅失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

// 获取餐厅分类列表
router.get('/categories', async (req, res) => {
  try {
    const { data, error } = await req.supabase
      .from('restaurants')
      .select('category')
      .not('category', 'is', null);
    
    if (error) throw error;
    
    const categories = [...new Set(data.map(item => item.category))].sort();
    
    res.json({
      success: true,
      data: categories,
      message: '餐厅分类获取成功'
    });
  } catch (error) {
    console.error('获取餐厅分类失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '获取餐厅分类失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

// 获取频率规则列表
router.get('/frequency-rules', (req, res) => {
  res.json({
    success: true,
    data: ['normal', 'often', 'rarely'],
    message: '频率规则获取成功'
  });
});

// 搜索餐厅
router.get('/search', async (req, res) => {
  try {
    const { keyword } = req.query;
    
    if (!keyword) {
      return res.status(400).json({
        success: false,
        data: null,
        message: '搜索关键词不能为空',
        error: {
          code: 400,
          type: 'ValidationError',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    const { data, error } = await req.supabase
      .from('restaurants')
      .select('*')
      .or(`name.ilike.%${keyword}%,category.ilike.%${keyword}%,notes.ilike.%${keyword}%`)
      .order('created_at', { ascending: false });
    
    if (error) throw error;
    
    res.json({
      success: true,
      data,
      message: '搜索餐厅成功'
    });
  } catch (error) {
    console.error('搜索餐厅失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '搜索餐厅失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

// 根据ID获取餐厅
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const { data, error } = await req.supabase
      .from('restaurants')
      .select('*')
      .eq('id', id)
      .single();
    
    if (error) {
      if (error.code === 'PGRST116') {
        return res.status(404).json({
          success: false,
          data: null,
          message: '餐厅不存在',
          error: {
            code: 404,
            type: 'NotFound',
            timestamp: new Date().toISOString(),
            path: req.path
          }
        });
      }
      throw error;
    }
    
    res.json({
      success: true,
      data,
      message: '餐厅获取成功'
    });
  } catch (error) {
    console.error('获取餐厅失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '获取餐厅失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

// 创建餐厅
router.post('/', async (req, res) => {
  try {
    const { name, category, frequency_rule, notes } = req.body;
    
    // 验证必填字段
    if (!name || !category || !frequency_rule) {
      return res.status(400).json({
        success: false,
        data: null,
        message: '餐厅名称、分类和频率规则为必填项',
        error: {
          code: 400,
          type: 'ValidationError',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    // 验证频率规则
    if (!['normal', 'often', 'rarely'].includes(frequency_rule)) {
      return res.status(400).json({
        success: false,
        data: null,
        message: '频率规则必须是 normal、often 或 rarely',
        error: {
          code: 400,
          type: 'ValidationError',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    const restaurantData = {
      id: uuidv4(),
      name: name.trim(),
      category: category.trim(),
      frequency_rule,
      notes: notes ? notes.trim() : null,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    };
    
    const { data, error } = await req.supabase
      .from('restaurants')
      .insert([restaurantData])
      .select()
      .single();
    
    if (error) throw error;
    
    res.status(201).json({
      success: true,
      data,
      message: '餐厅创建成功'
    });
  } catch (error) {
    console.error('创建餐厅失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '创建餐厅失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

// 更新餐厅
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, category, frequency_rule, notes } = req.body;
    
    // 验证频率规则（如果提供）
    if (frequency_rule && !['normal', 'often', 'rarely'].includes(frequency_rule)) {
      return res.status(400).json({
        success: false,
        data: null,
        message: '频率规则必须是 normal、often 或 rarely',
        error: {
          code: 400,
          type: 'ValidationError',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    const updateData = {
      updated_at: new Date().toISOString()
    };
    
    if (name !== undefined) updateData.name = name.trim();
    if (category !== undefined) updateData.category = category.trim();
    if (frequency_rule !== undefined) updateData.frequency_rule = frequency_rule;
    if (notes !== undefined) updateData.notes = notes ? notes.trim() : null;
    
    const { data, error } = await req.supabase
      .from('restaurants')
      .update(updateData)
      .eq('id', id)
      .select()
      .single();
    
    if (error) {
      if (error.code === 'PGRST116') {
        return res.status(404).json({
          success: false,
          data: null,
          message: '餐厅不存在',
          error: {
            code: 404,
            type: 'NotFound',
            timestamp: new Date().toISOString(),
            path: req.path
          }
        });
      }
      throw error;
    }
    
    res.json({
      success: true,
      data,
      message: '餐厅更新成功'
    });
  } catch (error) {
    console.error('更新餐厅失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '更新餐厅失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

// 删除餐厅
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const { error } = await req.supabase
      .from('restaurants')
      .delete()
      .eq('id', id);
    
    if (error) throw error;
    
    res.status(204).send();
  } catch (error) {
    console.error('删除餐厅失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '删除餐厅失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

// 批量删除餐厅
router.delete('/batch', async (req, res) => {
  try {
    const { ids } = req.body;
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        data: null,
        message: 'ids 必须是非空数组',
        error: {
          code: 400,
          type: 'ValidationError',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    const { error } = await req.supabase
      .from('restaurants')
      .delete()
      .in('id', ids);
    
    if (error) throw error;
    
    res.status(204).send();
  } catch (error) {
    console.error('批量删除餐厅失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '批量删除餐厅失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

module.exports = router;